<?php
$o_server = new Swoole\WebSocket\Server( "0.0.0.0", 8000 );
// 握手完毕，创建了一个ws链接

$o_server->on( 'open', function ( Swoole\WebSocket\Server $o_server, $o_request ) {
    echo "server: handshake success with fd{ $o_request->fd }\n";
} );
// 收到消息时候
$o_server->on( 'message', function ( Swoole\WebSocket\Server $o_server, $o_frame ) {

    echo "receive from {$o_frame->fd}:{$o_frame->data},opcode:{$o_frame->opcode},fin:{$o_frame->finish}\n";

    $o_server->push( $o_frame->fd, date("Y-m-d H:i:s").":".$o_frame->data);
});
// 链接被关闭时候
$o_server->on( 'close', function ($o_server, $i_fd) {
    echo "client {$i_fd} closed\n";
});
$o_server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
    global $o_server;//调用外部的server
    // $server->connections 遍历所有websocket连接用户的fd，给所有用户推送
    $pushed=0;
    foreach ($o_server->connections as $fd) {
        // 需要先判断是否是正确的websocket连接，否则有可能会push失败
        if ($o_server->isEstablished($fd)) {
            $o_server->push($fd, $request->get['message']);
           $pushed++;
        }
    }
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end($pushed);
});

// 开始启动
$o_server->start();

